import axios from 'axios';
import store from '../store'
import {addCookie,getCookie} from "./addCookie"
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
//axios.defaults.timeout = 5000;
axios.defaults.baseURL ='http://api.staging.mchain.one/';
//axios.defaults.baseURL ='https://py.mchain.one/';

axios.interceptors.request.use(
  config => {    
    config.headers = {

    }  
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);


//http response 拦截器
axios.interceptors.response.use(
  response => {
    if(response.data.errCode ==2){
      router.push({
        path:"/login",
        querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
      })
    }
    return response;
  },
  error => {
      
    return Promise.reject(error)
  }
)

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(`${url}?id=${getCookie('uid')}`,{
      params:params
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}
export function getlogin(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(`${url}`,{
      params:params
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function post(url,data = {},config){
   return new Promise((resolve,reject) => {

   axios.post(`${url}?id=${getCookie('uid')}`,data,config)
          .then(response => {
            resolve(response);
          },err => {
            reject(err)
          })
   })
 }
 export function postlogin(url,data = {}){
   return new Promise((resolve,reject) => {
   axios.post(`${url}`,data)
          .then(response => {
            resolve(response);
          },err => {
            reject(err)
          })
   })
 }

 /**
 * 封装patch请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.patch(`${url}?id=${getCookie('uid')}`,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}

 /**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.put(`${url}?id=${getCookie('uid')}`,data)
         .then(response => {
           resolve(response.data);
         },err => {
           reject(err)
         })
  })
}